﻿using JetBrains.Annotations;
using Microsoft.AspNetCore.SignalR;
using My.Application.Contracts.Orders;
using My.Application.Contracts.Orders.Dtos;
using My.Application.Hubs;
using My.Domain.Orders;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Uow;

namespace My.Application.Orders
{
    public class OrderService : ApplicationService, IOrderService
    {
        private readonly IOrderRepository _orderRepository;
        private readonly IHubContext<ChatHub> _hubContext;

        public OrderService(IOrderRepository orderRepository,
            IHubContext<ChatHub> hubContext)
        {
            _orderRepository = orderRepository;
            _hubContext = hubContext;
        }

        public async Task<OrderDto> CreateOrderAsync([NotNull] CreateOrderDto input)
        {
            await _hubContext.Clients.All.SendAsync("ReceiveMessage", "aaaa");
            Random random = new Random();
            var no = random.Next(10000, 100000);
            //实例化订单
            var order = new Order(GuidGenerator.Create(), no.ToString());
            input.OrderLines.ForEach(ol => { order.AddOrderLine(ol.ProductId, ol.Count); });
            await _orderRepository.InsertAsync(order);
            return ObjectMapper.Map<Order, OrderDto>(order);
        }

        public async Task<OrderDto> UpdateOrderAsync(Guid id, UpdateOrderDto input)
        {
            var entity = await _orderRepository.GetOrderAsync(id);
            entity.SetReferenceNo("50001");
            await _orderRepository.UpdateAsync(entity);
            CurrentUnitOfWork.OnCompleted(async () => await SendMessageAsync(id));
            return null;
        }
        private async Task SendMessageAsync(Guid id)
        {
            using (var uow = UnitOfWorkManager.Begin(requiresNew: false))
            {
                var orderQuery = await _orderRepository.GetQueryableAsync();
                var order = await AsyncExecuter.FirstOrDefaultAsync(orderQuery.Where(x => x.Id == id && x.ReferenceNo == "50001"));
            }
        }
    }

    public interface ITestInterface
    {
        void PrintMessage(string message);
    }

    public class TestInterface : ITestInterface
    {
        public virtual void PrintMessage(string message)
        {

        }
    }
}
